<?php
namespace Weixin\Controller;
use Think\Controller;
class IndexController extends Controller {
public function _initialize(){
	header("content-type:text/html;charset=utf-8");
	//1将 timestamp ,nonce ,token 按字典排序
		$timestamp=$_GET['timestamp'];
		$nonce   =$_GET['nonce'];
		$token= 'zhongqihengfu2016';
		$signature=$_GET['signature'];
		$array=array($timestamp,$nonce,$token);
		sort($array);
		//2将排序后的三个参数拼接用sha1 加密
		$tmpstr=implode('',$array);
		$tmpstr=sha1($tmpstr);
		//3将加密后的字符创鱼signature对比判断是否来自微信
		if ($tmpstr==$signature) {
			echo $_GET['echostr'];
			exit;
		}
}
/*
$url 接口url string
$type 请求类型 string
$res 返回数据类型 string
$arr post 请求参数 string
*/
function http_curl($url,$type="get",$res="json",$arr)
{
	header("content-type:text/html;charset=utf-8");
	// 初始化url
	$ch=curl_init();
	// 设置curl的参数
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	if ($type == "post") {
		curl_setopt($ch,CURLOPT_POST,1);
		curl_setopt($ch,CURLOPT_POSTFIELDS,$arr);
	}
	// 采集
	$output=curl_exec($ch);
	// 4关闭
	curl_close($ch);
	if ($res=='json') {
		if (curl_errno($ch)) {
			return curl_error($ch);
		}else{
			return json_decode($output,true);
		}
		
	}
}
// 全局 accessToken
//    public function getWxAccessToken1()
// {
	// 	$appid='wx770f9d3da4b072d4';
	// 	$appsecret="5d9b1fde1c7913522ef2ab52c3b6236c";
	// 	// 请求地址
	// 	 $url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
		// 		// 初始化url
		// 		$ch=curl_init();
		// 		// 设置curl的参数
		// 		curl_setopt($ch,CURLOPT_URL,$url);
		// 		curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
		// 		// 采集
		// 		 $res=curl_exec($ch);
		// 		// 4关闭
		// 		curl_close($ch);
	// 	if(curl_error($ch)){
		// 		dump(curl_error($ch));
		// 		}
		// 		$arr=json_decode("$res",true);

//     echo "<pre>";
	// print_r ($arr);
	// 	echo "</pre>";
// }
// 获取微信服务器
public function getServerIp()
{
	$accssToken="sdk9NA5OA5KPCdHw4f2kAAbIIRAenN4vqAv5vwFgrlTcFWDI0BJ9stzTqsduAXPwxhNzc06AKRHF76GO5waSKAkKcMPFzcqQU67OKOe6Hch2XdkpdY9MHZ5HelN8oafnNHVjAAAICQ";
	$url="https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=".$accssToken;
	// 初始化url
	$ch=curl_init();
	// 设置curl的参数
	curl_setopt($ch,CURLOPT_URL,$url);
	curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
	// 采集
	$res=curl_exec($ch);
	// 4关闭
	curl_close($ch);
if(curl_error($ch)){
	dump(curl_error($ch));
	}
	$arr=json_decode("$res",true);

    echo "<pre>";
	print_r ($arr);
	echo "</pre>";
}
// 返回access_token
public function getWxAccessToken()
{

// 将access_token存入session
	if ($_SESSION['access_token']&&$_SESSION['expire_time']>time()) {
		return $_SESSION['access_token'];
	}else{
		// 如果access_token不存在重新获取
	$appid='wx770f9d3da4b072d4';
	$appsecret="5d9b1fde1c7913522ef2ab52c3b6236c";
	// 请求地址
	$url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
	$res=$this->http_curl($url,'get');
	$access_token=$res['access_token'];
	$_SESSION['access_token']=$access_token;
	$_SESSION['expire_time']=time()+7000;  
	return $access_token;
	}
}
// 自定义菜单
public function defineItem()
{
	header("content-type:text/html;charset=utf-8");
	//创建微信菜单
	// 目前微信接口的条用方式都是通过curl post/get方式
  echo $access_token=$this->getWxAccessToken();
	
	$url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token=".$access_token;
	$postArr=array(
		'button'=>array(
			array(
				'name'=>urlencode('公社大门'),
				'sub_button'=>array(
					array(
					'name'=>urlencode('社区主页'),
					'type'=>'view',
					'url'=>'http://hubao.ynten.com',
						),//第一个二级菜单
					// array(
					// 	'name'=>urlencode('精彩活动'),
					// 	'type'=>'view',
					// 	'url'=>'http://www.baidu.com',
					// 	),//第二个二级菜单
					 array(
						'name'=>urlencode('个人中心'),
						'type'=>'view',
						'url'=>'http://hubao.ynten.com/Weixin/Index/getBaseInfo',
						),//第二个二级菜单
							),
				'type'=>'click',
				'key'=>'itme1',
			),//第一个一级菜单
			array(
				'name'=>urlencode('领取福利'),
				'type'=>'view',
				'url'=>'http://hubao.ynten.com/Member',
				),//第二个一级菜单
			array(
					'name'=>urlencode('了解公社'),
					'type'=>'view',
					'url'=>'http://hubao.ynten.com/Member',
			),//第三个一级菜单
			)
		);
	   
  $postJson=urldecode(json_encode($postArr)); 
	$res=$this->http_curl($url,'post','json',$postJson);
	var_dump($res);

   
}

public  function getBaseInfo()
        {
            //获取code
            $appid='wx770f9d3da4b072d4';
            $redirect_uri="http://hubao.ynten.com/Weixin/Index/getUserOpenId";
            $url=urldecode("https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appid."&redirect_uri=".$redirect_uri."&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect");
                 header("location:".$url);
           
        }
      public  function getUserOpenId()
        {
            //获取到网页授权的access_token;
            $appid='wx770f9d3da4b072d4';
            $appsecret="5d9b1fde1c7913522ef2ab52c3b6236c";
            $code=I("get.code");
            $url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$appsecret."&code=$code&grant_type=authorization_code ";
            //拉取用户openid
			$res=$this->http_curl($url,'get');
			$access_token=$res['access_token'];
			$openid=$res["openid"];
			// 拉取用户信息
			// $url="https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN ";
			// $res=$this->http_curl($url);	   
			// 	$user=M("User");
			// 	$data["openid"]=$res["openid"];
			// 	$data['username']=$res['nickname'];
			// 	$data['sex']=$res['sex'];
			// 	$data['createtime']=date("Y-m-d H:i:s",time());
			// 	$data["tsrc"]=$res['headimgurl'];	 
			// 	$OpenidArr=$user->where("openid='{$res["openid"]}'")->find();    
			// if (!empty($OpenidArr)) {
			// 	$u=$OpenidArr['id'];
			// 	 $this->redirect("http://hubao.ynten.com/Member/index/user/".$u);
			// }else{
			// 	 $u=$user->add($data);
			// 	 $Qian=M("Qianbao");
			// 	 $Ua['uid']=$u;
			// 	 $Qian->add($Ua);
			// 	$this->redirect("http://hubao.ynten.com/Member/index/user/".$u);
			// }

   //      }
   			$url="https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$openid."&lang=zh_CN ";
			$res=$this->http_curl($url);	   
				$user=M("User");
				$data["openid"]=$res["openid"];
				$data['username']=$res['nickname'];
				$data['sex']=$res['sex'];
				$data['createtime']=date("Y-m-d H:i:s",time());
				$data["tsrc"]=$res['headimgurl'];	 
				$OpenidArr=$user->where("openid='{$res["openid"]}'")->find();    
			if (!empty($OpenidArr)) {
				$u=$OpenidArr['id'];
				$_SESSION['user']=$u;
				 $this->redirect("http://hubao.ynten.com/Member/index/user/".$u);
			}else{
				if (!empty($data)) {
				 $u=$user->add($data);
				 $_SESSION['user']=$u;
				 $Qian=M("Qianbao");
				 $Ua['uid']=$u;
				 $Qian->add($Ua);
				$this->redirect("http://hubao.ynten.com/Member/index/user/".$u);
				}

			}
		}

}